<?php

namespace app\weixin\controller;
use think\Db;

class WxUser extends Base{

    public function _initialize(){
        parent::_initialize();
    }

    public function user_list(){
        $map = [];
        $start = input("start");
        $end = input("end");
        $display_name = input("display_name");
        if(!empty($start) && empty($end)){
            $map["create_time"] = array("egt",strtotime($start));
        }else if(!empty($end) && empty($start) ){
            $map["create_time"] = array("elt",strtotime($end));
        }else if(!empty($start) && !empty($end)){
            $map["create_time"][] = array("egt",strtotime($start));
            $map["create_time"][] = array("elt",strtotime($end));
        }
        if(!empty($display_name)){
            $map["display_name"] = [
                'like',
                "%$display_name%" 
            ];
        }

        $pagesize = config('paginate')['list_rows'];//每页数量
        $param=request()->param(); //获取url参数
        $lists = db('user')->where($map)->order('id desc')->paginate($pagesize,false,array('query' => array_splice($param,1)));
        $this->assign("lists",$lists);
        $this->assign("page", $lists->render());
        return $this->fetch("user_list");
    }

    public function user_goods(){
        $pagesize = config('paginate')['list_rows'];//每页数量
        $param=request()->param(); //获取url参数
        $uid = substr($param['uid'],0,strpos($param['uid'], '?'));
        $lists = db('user_goods')->where(['user_id'=>$uid])->order('id desc')->paginate($pagesize,false,array('query' => array_splice($param,1)));
        $this->assign("lists",$lists);
        $this->assign("page", $lists->render());
        return $this->fetch();
    }

    public function user_info(){
        $pagesize = config('paginate')['list_rows'];//每页数量
        $param=request()->param(); //获取url参数
        $uid = substr($param['uid'],0,strpos($param['uid'], '?'));
        $lists = db('user_info_extend')->where(['user_id'=>$uid])->order('id desc')->paginate($pagesize,false,array('query' => array_splice($param,1)));
        $this->assign("lists",$lists);
        $this->assign("page", $lists->render());
        return $this->fetch();
    }
    
    public function user_detail(){
        $pagesize = config('paginate')['list_rows'];//每页数量
        $param=request()->param(); //获取url参数
        $uid = substr($param['uid'],0,strpos($param['uid'], '?'));
        $lists = db('user')->where(['id'=>$uid])->order('id desc')->paginate($pagesize,false,array('query' => array_splice($param,1)));
        // dump($lists);die();
        $this->assign("lists",$lists);
        $this->assign("page", $lists->render());
        return $this->fetch();
    }

    public function user_anwser(){
        $pagesize = config('paginate')['list_rows'];//每页数量
        $param=request()->param(); //获取url参数
        $uid = substr($param['uid'],0,strpos($param['uid'], '?'));
        $lists = db('questions ')->
                 alias('q')->
                 join('user_answer_question aq','aq.qid = q.id')->
                 join('knowledge_subject k','k.id = q.subject_id')->
                 field('q.id,k.name, q.title ,count(q.id) as anwser_num')->
                 group('q.id')->
                 where(['aq.user_id'=>$uid])->order('aq.id desc')->paginate($pagesize,false,array('query' => array_splice($param,1)));
//        dump($lists);exit;
        $this->assign("lists",$lists);
        $this->assign("page", $lists->render());
        return $this->fetch();
    }

    //上传机器人用户文件
    function setting() {
        $map=[];
        $pagesize = config('paginate')['list_rows'];//每页数量
        $param=request()->param(); //获取url参数

        $list = db( 'robot_batch_record' )->where ( $map )->order ( 'id desc' )->paginate($pagesize,false,array('query' => array_splice($param,1)));
        $grad = db('grad')->order('sort')->select();//段位
        $this->assign('lists',$grad);

        $this->assign ( 'list_data',$list );
        $this->assign ( 'page', $list->render() );
        $this->assign ( 'status_arr', ['0'=>'作废','1'=>'未处理','2'=>'已处理','-1'=>'处理失败']);
         
        return $this->fetch();
    }

    //保存信息
    function save_setting() {
        \think\Loader::import('org.Excel', EXTEND_PATH);//导入第三方类库文件

        if(request()->isPost()){
            $post = request()->post();
            $import_total = \Excel::excel_get_data_size(realpath(UPLOAD_PATH).$post['url']);

            $gid = $post['gid'];
            $post['grad_name'] = db('grad')->where(['id'=>$gid])->value('name');

            $post['batch_no'] = 'BN'.date('YmdHis');
            $post['import_total'] = $import_total-1;//从第二条开始计算
            $post['create_time'] = time();
            unset($post['file_id']);
            $res = db('robot_batch_record')->insertGetId($post);
            if(!empty($res)){
                $this->success('添加成功！');
            }else{
                $this->error('添加失败！');
            }
        }
    }

    //导入用户
    function import_user(){
        $id = input('id');//批次记录id
        $gid = input('gid',1);//科目id
        $data_arr = [];

        if(!empty($id) && !empty($gid)){
            $res = db('robot_batch_record')->where(['id'=>$id,'status'=>1])->find();
            if(empty($res))$this->error('导入失败，该批次数据已处理!');
            \think\Loader::import('org.Excel', EXTEND_PATH);//导入第三方类库文件
            $start=2;//起始行
            $limit=10000;//最大10000数量
            $data = \Excel::excel_get_data(realpath(UPLOAD_PATH).$res['url'],$start,$limit);//读取excel数据
            $json['keep'] = $data['keep'];
            $json['start'] = $data['start'];
            $json['progress'] = $data['progress'];
            
            $i=0;
            $user_ids = [];
            $user_last_id = db('user')->order('id desc')->value('id');//最大用户id

            foreach($data['data'] as $row => $val){
                $uid = $user_last_id+$i+50;//50基数

                $user_ids[$i]['user_id'] = $uid;
                $data_arr[$i]['id'] = $uid;
                $data_arr[$i]['display_name'] = $val['A'];
                $data_arr[$i]['avatar'] = !empty($val['B'])?$val['B']:SITE_URL.'/static/images/avatar/head_default.gif';
                $data_arr[$i]['sex'] = $val['C']=='男' ? 1:0;
                $data_arr[$i]['province'] = $val['D'];
                $data_arr[$i]['city'] = $val['E'];
                $data_arr[$i]['grad_id'] = $res['gid'];//段位
                $data_arr[$i]['grad_name'] = $res['grad_name'];
                $data_arr[$i]['robot_rule_type'] = $res['rule_type'];//机器人规则类型
                $data_arr[$i]['openid'] = 'rb_'.getRandChar(32);//openid
                $data_arr[$i]['is_robot'] = 1;//用户类型
                $data_arr[$i]['points'] = 10000;//金币

                $data_arr[$i]['status'] = 1;//通过
                $data_arr[$i]['create_time'] = time();

                $i++;
            }
            
            //var_export($data_arr);exit;
            if(!empty($data_arr)){//导入
                Db::startTrans();
                try {
                    $ret = db('user')->insertAll($data_arr);
                    if($ret){
                        db('user_info_extend')->insertAll($user_ids);//扩展表
                        db('robot_batch_record')->where(['id'=>$id])->update(['status'=>2]);//更新批量导入批次记录
                    }
                    Db::commit();
                    $this->success('导入成功！');
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error('导入失败！');
                }
            }else{
                $this->error('导入失败！');
            }
            //var_export($data_arr);exit;
        }else{
            $this->error('导入失败！');
        }

    }

} 